const app = getApp()
//小程序蓝牙只支持BLE低功耗蓝牙
Page({
  //改变inputText的值，多次调用即可
  //收到是字符串
  data: {

    inputText: '255 01 02 03',
    valueSlier: 50,
    wendu: '',
    shidu: '',
    adc: '',
    receiveArry: [],
    name: '',
    connectedDeviceId: '',
    serviceId: 0,
    characteristics: {},
    connected: true,
    colorData: {
      //基础色相，即左侧色盘右上顶点的颜色，由右侧的色相条控制
      hueData: {
        colorStopRed: 255,
        colorStopGreen: 0,
        colorStopBlue: 0,
      },
      //选择点的信息（左侧色盘上的小圆点，即你选择的颜色）
      pickerData: {
        x: 0, //选择点x轴偏移量
        y: 480, //选择点y轴偏移量
        red: 0,
        green: 0,
        blue: 0,
        hex: '#000000'
      },
      //色相控制条的位置
      barY: 0
    },
    rpxRatio: 1, //此值为你的屏幕CSS像素宽度/750，单位rpx实际像素
  },
  //16进制字符串转为ArrayBuffer
  hexStringToArrayBuffer: function(str) {
    if (!str) {
      return new ArrayBuffer(0);
    }
    var buffer = new ArrayBuffer(str.length);
    let dataView = new DataView(buffer)
    let ind = 0;
    for (var i = 0, len = str.length; i < len; i += 2) {
      let code = parseInt(str.substr(i, 2), 16)
      dataView.setUint8(ind, code)
      ind++
    }
    return buffer;
  },
  eventSlider: function(e) {
    var that = this
    this.setData({
      valueSlier: e.detail.value
    })
    let buffer = new ArrayBuffer(6)
    let dataView = new DataView(buffer)
    dataView.setUint8(4, 187)
    dataView.setUint8(5, e.detail.value)

    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  onred: function() {
    var that = this

    let buffer = that.hexStringToArrayBuffer("10");
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  offred: function() {
    var that = this

    let buffer = that.hexStringToArrayBuffer("11");
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  ongreed: function() {
    var that = this

    let buffer = that.hexStringToArrayBuffer("12");
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  offgreed: function() {
    var that = this

    let buffer = that.hexStringToArrayBuffer("13");
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  onblue: function() {
    var that = this

    let buffer = that.hexStringToArrayBuffer("14");
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  offblue: function() {
    var that = this

    let buffer = that.hexStringToArrayBuffer("15");
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }

  },
  onLoad: function(options) {
    var that = this
    wx.getSystemInfo({
      success(res) {
        that.setData({
          rpxRatio: res.screenWidth / 750
        })
      }
    })
    console.log(options)
    that.setData({
      name: options.name,
      connectedDeviceId: options.connectedDeviceId
    })
    wx.getBLEDeviceServices({
      deviceId: that.data.connectedDeviceId,
      success: function(res) {
        var all_UUID = res.services;
        var index_uuid = -1;
        var UUID_lenght = all_UUID.length;
        /* 遍历服务数组 */
        for (var index = 0; index < UUID_lenght; index++) {
          var ergodic_UUID = all_UUID[index].uuid; //取出服务里面的UUID
          //  console.log('接收到ergodic_UUID数据：' + ergodic_UUID)

     
          if (ergodic_UUID == '00020103-0305-0607-0809-0A0B0C0D1910') {
            index_uuid = index;
          };
    
        };
        if (index_uuid == -1) {
          wx.showModal({
            title: '提示',
            content: '非我方出售的设备',
            showCancel: false,
            success: function(res) {
              that.setData({
                searching: false
              })
            }
          })
        }
        that.setData({
          serviceId: res.services[index_uuid].uuid
        })
        // 服务特征值是干嘛的：每个服务都包含了一组特征值用来描述服务的一些属性，获取是否可读，是否可写，是否可以开启notify通知等，当你跟蓝牙通信时需要这些特征值ID来传递数据。
        wx.getBLEDeviceCharacteristics({
          deviceId: options.connectedDeviceId,
          serviceId: res.services[index_uuid].uuid,
          success: function(res) {
            that.setData({
              characteristics: res.characteristics
            })
            // 开启notify后可以监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification
            wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: options.connectedDeviceId,
              serviceId: that.data.serviceId,
              characteristicId: that.data.characteristics[0].uuid,
              success: function(res) {
                console.log('启用notify成功')
              },
              fail(res) {
                console.log(res)
              }
            })
          }
        })
      }
    })
    wx.onBLEConnectionStateChange(function(res) {
      console.log(res.connected)
      that.setData({
        connected: res.connected
      })
    })
    //ArrayBuffer转为16进制数
    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function(bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }

    // 16进制数转ASCLL码
    function hexCharCodeToStr(hexCharCodeStr) {
      var trimedStr = hexCharCodeStr.trim();
      var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
      var len = rawStr.length;
      var curCharCode;
      var resultStr = [];
      for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16);
        resultStr.push(String.fromCharCode(curCharCode));
      }
      return resultStr.join("");
    }

    wx.onBLECharacteristicValueChange(function(res) {
      // 将bufferArray类型转为string类型
      console.log('接收到数据：' + app.buf2string(res.value))
      // 因为buffer不能直接在console.log里输出，会显示null
      var hex = ab2hex(res.value)

      // console.log('接收到数据：' + hex)
      //console.log(parseInt(hex, 16));
      that.setData({
        wendu: app.buf2string(res.value).substr(0, 2),
        shidu: app.buf2string(res.value).substr(2,2),
       adc: app.buf2string(res.value).substr(4,6)
      })
    })
  },
  onChangeColor(e) {
    //返回的信息在e.detail.colorData中
    var that = this;
    let getColor = e.detail.colorData.pickerData;
    // console.log('红色', (getColor.red))
    // console.log('绿色', (getColor.green))
    // console.log('蓝色', (getColor.blue))

    let buffer = new ArrayBuffer(10)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 170)
    dataView.setUint8(1, getColor.red)
    dataView.setUint8(2, getColor.green)
    dataView.setUint8(3, getColor.blue)
    console.log("buff is", buffer);
    if (that.data.connected) {
      //写入数据
      wx.writeBLECharacteristicValue({
        deviceId: that.data.connectedDeviceId,
        serviceId: that.data.serviceId,
        characteristicId: that.data.characteristics[0].uuid,
        value: buffer,
        success: function(res) {
          console.log('发送成功')
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '蓝牙已断开',
        showCancel: false,
        success: function(res) {
          that.setData({
            searching: false
          })
        }
      })
    }
  },
  onUnload: function() {
    wx.closeBLEConnection({
      deviceId: this.data.connectedDeviceId,
      success: function(res) {},
    })
  },



})